<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-width="100px"
    >
      <el-form-item label="设备名称" prop="name">
        <el-select
            v-model="formData.name"
            placeholder="选择设备"
            style="width: 515px"
        >
          <el-option
              v-for="item in equipmentNameList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检修时间" prop="repTime">
        <el-date-picker
            v-model="formData.repTime"
            type="datetime"
            placeholder="请选择检修时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="故障状态" prop="status">
<!--        <el-input v-model="formData.status" placeholder="请输入故障状态"/>-->
        <el-select
            v-model="formData.status"
            placeholder="选择故障状态"
            style="width: 515px"
        >
          <el-option
              v-for="item in troubleStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检修人" prop="repPerson">
<!--        <el-input v-model="formData.repPerson" placeholder="请输入检修人"/>-->
        <el-select
            v-model="formData.repPerson"
            placeholder="选择检修人"
            style="width: 515px"
        >
          <el-option
              v-for="item in tquipmentRepairmanStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检修费用" prop="repCost">
        <el-input v-model="formData.repCost" placeholder="请输入检修费用"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as RoleApi from '@/api/system/role'
import * as ProjectApi from '@/api/laboratory/report'

defineOptions({name: 'SystemRoleForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: "",  //设备名称
  repTime: "", //检修时间
  status: "", //故障状态
  repPerson: "",//检修人
  repCost: "",//检修费用
  remark: "",//备注
})
const formRules: any = reactive({
  name: [{required: true, message: '设备名称不能为空', trigger: 'change'}],
  repTime: [{required: true, message: '检修时间不能为空', trigger: 'blur'}],
  status: [{required: true, message: '故障状态不能为空', trigger: 'change'}],
  repPerson: [{required: true, message: '检修人不能为空', trigger: 'change'}],
  repCost: [{required: true, message: '检修费用不能为空', trigger: 'blur'}],
  remark: [{required: true, message: '备注不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

let equipmentNameList = ref([])
// 获取项目名称列表
const getEquipmentNameList = async () => {
  const data = await ProjectApi.getEquipmentNameList()
  console.log('获取名称列表', data.result)
  return data.result
}

// 获取设备维修状态
const getTroubleStatus = async () => {
  let aa = await ProjectApi.getEquipmentTypeList({pageNo: 1, pageSize: 100, dictType: 'troubleStatus'})
  let arr = []
  console.log('aa',aa)
  aa.list.forEach(item => {
    arr.push({
      label: item.label,
      value: item.value
    })
  })
  return arr;
}

// 获取设备检修人
const getEquipmentRepairmanList = async () => {
  let aa = await ProjectApi.getEquipmentTypeList({pageNo: 1, pageSize: 100, dictType: 'EquipmentRepairman'})
  let arr = []
  aa.list.forEach(item => {
    arr.push({
      label: item.label,
      value: item.value
    })
  })
  return arr;
}

// 设备故障状态列表
const troubleStatusList = ref([])
const tquipmentRepairmanStatusList = ref([])
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  equipmentNameList.value = await getEquipmentNameList()
  resetForm()
  troubleStatusList.value = await getTroubleStatus()
  console.log('troubleStatusList.value',troubleStatusList.value)
  tquipmentRepairmanStatusList.value = await getEquipmentRepairmanList()
  console.log('getEquipmentRepairmanList 检修人',tquipmentRepairmanStatusList.value)

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ProjectApi.getEquipmentMaintainById(id)
      formData.value = data.result
    } finally {
      formLoading.value = false
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: "",  //设备名称
    repTime: "", //检修时间
    status: "", //故障状态
    repPerson: "",//检修人
    repCost: "",//检修费用
    remark: "",//备注
  }
  formRef.value?.resetFields()

}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RoleApi.RoleVO
    if (formType.value === 'create') {
      await ProjectApi.addEquipmentMaintain(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProjectApi.updateEquipmentMaintain(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
